package com.acxiom.foodreview.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import com.acxiom.foodreview.service.SysUserDetailsService;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	@Autowired
	SysUserDetailsService sysUserDetailsService;

	/**
	 * Request层面的配置，对应XML Configuration中的<http>元素
	 */
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.csrf().disable()
		.authorizeRequests()
		.and()
			.formLogin()
			.loginPage("/login")
			.failureUrl("/login?error")
			.permitAll()
		.and()
			.logout()
			.logoutUrl("/logout")
			.permitAll()
		.and()
			.sessionManagement()
			.maximumSessions(1)
			.expiredUrl("/expired")
		.and()
		.and()
			.exceptionHandling()
			.accessDeniedPage("/accessDenied");
	}

	/**
	 * Web层面的配置，一般用来配置无需安全检查的路径
	 */
	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("/static/**","/druid/**","/api/**","/error");
	}

	/**
	 * 身份验证配置，用于注入自定义身份验证Bean和密码校验规则
	 */
	@Override
	public void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(sysUserDetailsService).passwordEncoder(new BCryptPasswordEncoder());
	}
}
